#!/bin/bash

echo "========================================"
echo "量化投资管理系统启动脚本"
echo "========================================"

# 检查Node.js是否安装
if ! command -v node &> /dev/null; then
    echo "❌ Node.js未安装，请先安装Node.js"
    exit 1
fi

# 检查Python是否安装
if ! command -v python3 &> /dev/null; then
    echo "❌ Python未安装，请先安装Python"
    exit 1
fi

echo "✅ 环境检查通过"

# 检查依赖是否安装
if [ ! -d "node_modules" ]; then
    echo "📦 安装前端依赖..."
    npm install
    if [ $? -ne 0 ]; then
        echo "❌ 前端依赖安装失败"
        exit 1
    fi
fi

# 检查后端虚拟环境
if [ ! -d "backend/venv" ]; then
    echo "📦 创建后端虚拟环境..."
    cd backend
    python3 -m venv venv
    cd ..
fi

# 激活虚拟环境并安装后端依赖
echo "📦 安装后端依赖..."
cd backend
source venv/bin/activate
pip install -r requirements.txt
if [ $? -ne 0 ]; then
    echo "❌ 后端依赖安装失败"
    exit 1
fi
cd ..

echo "✅ 依赖安装完成"

# 启动后端服务器
echo "🚀 启动后端服务器..."
cd backend
source venv/bin/activate
python run.py &
BACKEND_PID=$!
cd ..

# 等待后端启动
echo "⏳ 等待后端服务器启动..."
sleep 5

# 启动前端服务器
echo "🚀 启动前端服务器..."
npm run dev &
FRONTEND_PID=$!

echo "========================================"
echo "🎉 系统启动完成！"
echo "========================================"
echo "前端地址: http://localhost:3000"
echo "后端地址: http://localhost:8000"
echo "API文档: http://localhost:8000/docs"
echo "========================================"
echo "按 Ctrl+C 停止所有服务..."

# 等待用户中断
trap "echo '正在停止服务...'; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; exit" INT
wait 